from google.appengine.ext import db
from google.appengine.ext import webapp
import wsgiref.handlers


class DataStoreTemplate(db.Model):
	name = db.StringProperty(required = True)
	text = db.TextProperty(required = True)
	
class Creator(webapp.RequestHandler):
	def get(self):
	        self.response.out.write("""
	          <html>
	            <body>
	              <form method="post">
									Name:<input type="text" name="name">
	                <div><textarea name="content" rows="40" cols="60"></textarea></div>
	                <div><input type="submit" value="Add New Template"></div>
	              </form>
	            </body>
	          </html>""")
	
	def post(self):
		Entries = db.GqlQuery("SELECT * FROM DataStoreTemplate WHERE name=:1",self.request.get('name').lower())
		if Entries.count()!=0:
			Entries[0].text = db.Text(self.request.get('content'))
			Entries[0].put()
			self.get()
			return
		else:
			store = DataStoreTemplate(name=self.request.get('name').lower(),text=db.Text(self.request.get('content')))
			store.put()
			self.get()
		

def main():
  application = webapp.WSGIApplication([('.*', Creator)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()